import { NextRequest, NextResponse } from 'next/server'
import { requireAuth, withErrorHandling } from '@/lib/auth-middleware'
import { terminateSession } from '@/lib/auth-service'

export const DELETE = withErrorHandling(async (request: NextRequest, { params }: { params: Promise<{ id: string }> }) => {
  return requireAuth(request, async (req) => {
    try {
      // 从URL中提取会话ID
      const url = new URL(request.url)
      const sessionId = url.pathname.split('/').slice(-1)[0]
      
      if (!sessionId) {
        return NextResponse.json({
          success: false,
          error: '会话ID不能为空'
        }, { status: 400 })
      }
      
      // 不能终止当前会话
      const token = request.headers.get('authorization')?.replace('Bearer ', '') || ''
      const currentSessionResult = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/auth/me`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      const currentSession = await currentSessionResult.json()
      if (currentSession.success && currentSession.session?.id === sessionId) {
        return NextResponse.json({
          success: false,
          error: '不能终止当前会话'
        }, { status: 400 })
      }
      
      const success = await terminateSession(sessionId, req.user!.id)
      
      if (success) {
        return NextResponse.json({
          success: true,
          message: '会话终止成功'
        })
      } else {
        return NextResponse.json({
          success: false,
          error: '会话终止失败或会话不存在'
        }, { status: 404 })
      }
    } catch (error) {
      console.error('终止会话失败:', error)
      return NextResponse.json({
        success: false,
        error: '终止会话失败'
      }, { status: 500 })
    }
  })
})